package auth

import (
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/itstonight/ziyue/controller/rsp"
	"github.com/itstonight/ziyue/db"
	"github.com/itstonight/ziyue/models"
)

const (
	loginUserKey = "login_user"
	bearerPrefix = "Bearer "
)

func Middleware(ctx *gin.Context) {
	token := strings.Replace(ctx.GetHeader("Authorization"), bearerPrefix, "", 1)

	var tokenModel models.Token
	if err := db.Client.WithContext(ctx).Where("token = ?", token).Preload("User").First(&tokenModel).Error; err != nil {
		rsp.Abort(ctx, "未登录")
		return
	}

	ctx.Set(loginUserKey, tokenModel.User)
}

func IsAdmin(ctx *gin.Context) {
	Middleware(ctx)

	user := MustGetUser(ctx)

	if user.Role != 1 {
		rsp.FailWithMsg(ctx, "无权限")
		return
	}
}

func MustGetUser(ctx *gin.Context) *models.User {
	return ctx.MustGet(loginUserKey).(*models.User)
}
